/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package wcos.apiconnect;

import com.google.gson.Gson;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class APIProcess {

    private final String apiAddress;
    private final HashMap<String, String> queryModel;

    public APIProcess(String apiAddress, HashMap<String, String> queryModel) {
        this.apiAddress = apiAddress;
        this.queryModel = queryModel;
    }

    public <T> T ProcessData(Class<T> typeOfT)
            throws IntrospectionException, MalformedURLException, IOException {
        APIConnect connect = new APIConnect(apiAddress);

        String query = QueryStringBuilder(queryModel);
        InputStreamReader reader = connect.ApiJSonGet(query);        
        T result = new Gson().fromJson(reader, typeOfT);
        return result;
    }

    private String QueryStringBuilder(HashMap<String, String> queryModel) {
        StringBuilder sb = new StringBuilder();
        queryModel.entrySet().forEach((Map.Entry<String, String> e) -> {
            if (sb.length() > 0) {
                sb.append('&');
            }
            try {
                sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(e.getValue(), "UTF-8"));
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(APIProcess.class.getName()).log(Level.SEVERE, null, ex);
            }
        });

        return sb.toString();
    }
}
